    //
//  BigMapVC.m
//  WRY
//
//  Created by Yang on 12/2/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "BigMapVC.h"


@implementation BigMapVC{
    float distance;
}
@synthesize userCurrentLocation,locationManager;
@synthesize dataDict;
@synthesize localMap;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"返回"
																			   style:UIBarButtonItemStyleDone 
																			  target:self 
																			  action:@selector(donePressed:)] autorelease];
     self.locationManager = [[CLLocationManager alloc] init];
     self.locationManager.delegate = self;
     self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
     [self.locationManager startUpdatingLocation];
    
     self.localMap.delegate=self;
     [self setMapProporties:dataDict];//141107 zl
    
    
}

- (void)donePressed:(id)sender {
	[self dismissModalViewControllerAnimated:YES];
}


- (void)setMapProporties:(NSDictionary *)infoDict {

    if(self.localMap == nil){
        self.localMap.delegate = self;
        
    }
  
    dataDict = [[NSMutableDictionary alloc]initWithDictionary:infoDict];
	self.title = [infoDict objectForKey:@"EnterpriseName"];
	[self.localMap removeAnnotations:[self.localMap annotations]];
	if (![infoDict objectForKey:@"EnterpriseLongitude"] || ![infoDict objectForKey:@"EnterpriseLatitude"]) {
		return;
	}
   	MKCoordinateRegion theRegin;
	CLLocationCoordinate2D theCenter;
	
	NSString *lat=[NSString stringWithFormat:@"%@",[infoDict objectForKey:@"EnterpriseLatitude"]];
	NSString *lon=[NSString stringWithFormat:@"%@",[infoDict objectForKey:@"EnterpriseLongitude"]];
	if (![lat isEqualToString:@"<null>"] && ![lon isEqualToString:@"<null>"]) {
		theCenter.latitude =[lat floatValue];
		theCenter.longitude =[lon floatValue];
	}
    self.localMap.delegate = self;
	theRegin.center=theCenter;
	
	CLLocationCoordinate2D theCoordinate;
	theCoordinate.latitude =theCenter.latitude ;
	theCoordinate.longitude=theCenter.longitude;
	MapAnnotation * ano = [[MapAnnotation alloc] initWithCoords:theCoordinate name:[infoDict objectForKey:@"EnterpriseName"]];
	ano.subName=[infoDict objectForKey:@"EnterpriseName"];
	[self.localMap addAnnotation:ano];
	[ano release];
	
	MKCoordinateSpan theSpan;
    theSpan.latitudeDelta = 5;
    theSpan.longitudeDelta = 5;
	theRegin.span = theSpan;
    [self.localMap setCenterCoordinate:theCoordinate animated:YES];
	[self.localMap setRegion:theRegin];
	[self.localMap regionThatFits:theRegin];
  
	self.localMap.showsUserLocation = NO;
	
}
- (void)mapPinDetailPressed:(id)sender {
	UIAlertView *alert = [[UIAlertView alloc]
						  initWithTitle:@"地图导航" message:[NSString stringWithFormat: @"转到地图程序，导航到该公司?"]//,appName] 
						  delegate:self cancelButtonTitle:nil otherButtonTitles:@"确认",@"取消",nil];
	
	[alert show];
	[alert release];	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    
	[self.locationManager stopUpdatingLocation];
	self.locationManager.delegate = nil;
	[self.localMap release];
	[locationManager release];
	[userCurrentLocation release];
	[dataDict release];
    [super dealloc];
}
#pragma mark MapViewdelegate

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
	if ([annotation isKindOfClass:[MapAnnotation class]]) {
		static NSString *AnoViewIdentifier = @"voucherBigMapAnoView";
        MKAnnotationView *anoView=(MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnoViewIdentifier];
        if (!anoView) {
            MKAnnotationView *customPinView =[[[MKAnnotationView alloc] initWithAnnotation:annotation
                                                                                         reuseIdentifier:AnoViewIdentifier]autorelease];
            customPinView.canShowCallout = YES;
            customPinView.image = [UIImage imageNamed:@"mapPin.png"];
            UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            [button addTarget:self action:@selector(mapPinDetailPressed:) forControlEvents:UIControlEventTouchUpInside];
            customPinView.rightCalloutAccessoryView = button;
            return customPinView;
        }
        else
        {
            anoView.annotation=annotation;
            anoView.canShowCallout=YES;
            return anoView;
        }
		
	}
	return nil;
}
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    userCurrentLocation = [locationManager location];
	if(buttonIndex==0)
	{
		NSString* startLocation = [[NSString alloc] initWithString:@"当前位置"];
		NSString* finalLocation = [dataDict objectForKey:@"EnterpriseName"];
		NSString *urlString =[NSString stringWithFormat:@"http://maps.google.com/maps?daddr=%@@%@,%@&saddr=%@@%f,%f",[finalLocation stringByReplacingOccurrencesOfString:@" " withString:@"+"],
							  [dataDict objectForKey:@"EnterpriseLatitude"],[dataDict objectForKey:@"EnterpriseLongitude"],
							  [startLocation stringByReplacingOccurrencesOfString:@" " withString:@"+"],userCurrentLocation.coordinate.latitude,userCurrentLocation.coordinate.longitude];
		urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		[[UIApplication sharedApplication] openURL: [NSURL URLWithString: urlString]];
	}
	
}

#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
	
	self.userCurrentLocation = newLocation;
}

@end
